const { AppError } = require('../middlewares/errorHandler');
const { logger } = require('../utils/logger');
const cacheService = require('../services/cache.service');

class CacheController {
  /**
   * 获取缓存值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async get(ctx) {
    const { key } = ctx.params;
    const value = await cacheService.get(key);
    
    if (value === null) {
      throw new AppError(404, '缓存键未找到');
    }

    ctx.body = {
      status: '成功',
      data: { value }
    };
  }

  /**
   * 设置缓存值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async set(ctx) {
    const { key } = ctx.params;
    const { value, ttl } = ctx.request.body;

    const success = await cacheService.set(key, value, ttl);
    if (!success) {
      throw new AppError(500, '设置缓存值失败');
    }

    ctx.body = {
      status: '成功',
      message: '缓存值设置成功'
    };
  }

  /**
   * 删除缓存值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async delete(ctx) {
    const { key } = ctx.params;
    const success = await cacheService.del(key);

    if (!success) {
      throw new AppError(500, '删除缓存值失败');
    }

    ctx.body = {
      status: '成功',
      message: '缓存值删除成功'
    };
  }

  /**
   * 检查缓存键是否存在
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async exists(ctx) {
    const { key } = ctx.params;
    const exists = await cacheService.exists(key);

    ctx.body = {
      status: '成功',
      data: { exists }
    };
  }

  /**
   * 清除缓存
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async clear(ctx) {
    const success = await cacheService.clear();

    if (!success) {
      throw new AppError(500, '清除缓存失败');
    }

    ctx.body = {
      status: '成功',
      message: '缓存清除成功'
    };
  }

  /**
   * 获取哈希值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async getHash(ctx) {
    const { hash, key } = ctx.params;
    const value = await cacheService.hget(hash, key);

    if (value === null) {
      throw new AppError(404, '哈希键未找到');
    }

    ctx.body = {
      status: '成功',
      data: { value }
    };
  }

  /**
   * 设置哈希值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async setHash(ctx) {
    const { hash, key } = ctx.params;
    const { value } = ctx.request.body;

    const success = await cacheService.hset(hash, key, value);
    if (!success) {
      throw new AppError(500, '设置哈希值失败');
    }

    ctx.body = {
      status: '成功',
      message: '哈希值设置成功'
    };
  }

  /**
   * 删除哈希值
   * @param {Object} ctx - 上下文
   * @returns {Promise<void>}
   */
  async deleteHash(ctx) {
    const { hash, key } = ctx.params;
    const success = await cacheService.hdel(hash, key);

    if (!success) {
      throw new AppError(500, '删除哈希值失败');
    }

    ctx.body = {
      status: '成功',
      message: '哈希值删除成功'
    };
  }
}

module.exports = new CacheController(); 